from fastapi import APIRouter, Request, HTTPException, status
from .scheams import UserInfoRegResponse, UserInfoRegRequest
from .models import User
from . import models
from api.application.utils import wechat_tools, tools
from api.application.utils.jwt_tools import JwtToken
from tortoise.expressions import Q
from api.application import settings


app = APIRouter()


@app.post('/login')
async def login(data: dict, request:Request):
    request_mobile = data['mobile']
    request_password = data['password']
    request_sms_code = data['sms_code']
    request_wx_code = data['code']

    redis = request.app.state.redis
    redis_code = await redis.get(f'SMS_{request_mobile}')
    if redis_code is None:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="验证码已过期")
    if redis_code != request_sms_code:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="验证码错误，请重新输入")

    result = wechat_tools.get_wechat_info(request_wx_code)
    user = await models.User.filter(Q(mobile=request_mobile) | Q(openid=result['openid'])).first()
    if not user:
        raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail='当前用户不存在！')

    hashing = tools.Hashing()
    ret = hashing.verify(request_password, user.password)
    if not ret:
        raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail='当前账号或密码错误！')

    token = JwtToken.create_JWT({
        'id': user.id
    })
    await models.UserLoginHistory.create(user=user)

    await redis.setex(f'token_{user.id}', settings.JWT['expire_time'], token)

    await redis.delete(f'sms_{request_mobile}')

    return {
        'id': user.id,
        'nickname': user.nickname,
        'avatar': user.avatar,
        'code': status.HTTP_200_OK,
        'err_msg': '用户登陆成功',
        'status': 'Success',
        'token': token,
    }




@app.post('/register', response_model=UserInfoRegResponse)
async def register(request: Request, user_info: UserInfoRegRequest):
    print("user_info:::", user_info)
    mobile = user_info.mobile
    code = user_info.code
    username = user_info.mobile
    avatar = user_info.avatarUrl
    nickname = user_info.nickName
    gender = user_info.gender
    result = await User.filter(mobile=mobile).first()
    if result:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='该手机号已注册过，不能重复注册')

    wechat_user = wechat_tools.get_wechat_info(code)

    user = await User.filter(openid=wechat_user['openid']).first()
    if user:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='该微信号已注册过，不能重复注册')

    user_sms = user_info.sms_code
    redis = request.app.state.redis
    redis_code = await redis.get(f'SMS_{mobile}')
    print("user_sms:::", user_sms)
    print("redis_code:::", redis_code)

    if not redis_code:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="验证码已过期，请重新发送")

    if redis_code != user_sms:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="验证码错误")

    if redis_code == user_sms:
        user = await User.create(
            **dict(user_info),
            username=username,
            avatar=avatar,
            nickname=nickname,
            sex=gender,
            openid=wechat_user['openid']
        )

        await redis.delete(f'SMS_{mobile}')
    return {
        'id': user.id,
        'avatar': user.avatar,
        'nickname': user.nickname,
        'code': status.HTTP_200_OK,
        'err_msg': '注册成功',
        'status': 'Success',
        'token': JwtToken.create_JWT({
            "id": user.id,
            "username": user.username
        })
    }
